#!/bin/sh
#
# mediatomb This script starts and stops the mediatomb daemon
#
# chkconfig: - 95 30
# processname: mediatomb
# description: mediatomb is a daemon process which provides a UPnP service
# config: /etc/mediatomb
# config: /etc/mediatomb/config.xml
# pidfile: /var/run/mediatomb.pid


# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# Set default mediatomb configuration.

# either make an installation in /etc/mediatomb and leave this blank,
# or specify an alternative config file location using the -c option
# Note: be aware, that -i parameter is used to set the ip of the 
# interface specified above

. /etc/mediatomb.conf

###############################
# make sure to run it as nobody
MEDIATOMB="-d -u $MT_USER -g $MT_GROUP -P $MT_PIDFILE -l $MT_LOGFILE -m $MT_HOME -f $MT_CFGDIR -p $MT_PORT"

[ -f /usr/bin/mediatomb ] || exit 0
[ ${MT_INTERFACE} = "NOT_SET" ] && echo "Please edit /etc/mediatomb.conf and change \
the MT_INTERFACE variable to your network device (eth0, eth1, etc.)" && exit 0

PATH=$PATH:/usr/bin:/usr/local/bin

# By default it's all good
RETVAL=0

# See how we were called.
case "$1" in
  start)
    # Start daemon.
    echo -n "Applying multicast settings to $MT_INTERFACE... "
    # those settings are necessary for us to react to M-SEARCH requests
    route add -net 239.0.0.0 netmask 255.0.0.0 $MT_INTERFACE >/dev/null 2>&1
    ifconfig $MT_INTERFACE allmulti
    touch $MT_PIDFILE
    chown mediatomb $MT_PIDFILE

    mkdir -p "/$MT_HOME/$MT_CFGDIR"
    chown mediatomb "/$MT_HOME/$MT_CFGDIR"
    
    echo -n "Starting mediatomb: "
    
    daemon $NICELEVEL mediatomb $MEDIATOMB -e $MT_INTERFACE $MT_OPTIONS
    
    RETVAL=$?
        echo
        [ $RETVAL = 0 ] && touch /var/lock/subsys/mediatomb
        ;;
  stop)
        # Stop daemons.
        echo -n "Shutting down mediatomb: "
        killproc mediatomb
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/mediatomb
        ;;
  restart)
        $0 stop
        $0 start
        ;;
  condrestart)
       [ -e /var/lock/subsys/mediatomb ] && $0 restart
       ;;
  status)
    status mediatomb
    RETVAL=$?
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status|condrestart}"
    RETVAL=1
    ;;
esac

exit $RETVAL
